import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/LoginView.vue'),
            meta: { requiresAuth: false },
        },
        {
            path: '/home',
            name: 'home',
            component: () => import('../views/PageIndexView.vue'),
            meta: { requiresAuth: true },
            children: [
                {
                    path: 'overview',
                    name: 'overview',
                    component: () => import('../views/pages/Overview.vue'),
                    meta: { requiresAuth: true },
                },
                {
                    path: 'enterprise',
                    name: 'enterprise',
                    component: () => import('../views/pages/Enterprise.vue'),
                    meta: { requiresAuth: true },
                },
                {
                    path: 'notification',
                    name: 'notification',
                    component: () => import('../views/pages/Notification.vue'),
                    meta: { requiresAuth: true },
                },
                {
                    path: 'dataManage',
                    name: 'dataManage',
                    meta: { requiresAuth: true },
                    redirect: '/home/dataManage/all',
                    children: [
                        {
                            path: 'all',
                            name: 'dataManage-all',
                            meta: { requiresAuth: true },
                            component: () => import('../views/pages/DataManage.vue'),
                        },
                        {
                            path: 'pending',
                            name: 'dataManage-pending',
                            meta: { requiresAuth: true },
                            component: () => import('../views/pages/DataManage.vue'),
                        },
                    ],
                },
                // 默认重定向到概况页
                {
                    path: '',
                    redirect: '/home/overview',
                },
            ],
        },
        // 根路径重定向到登录页
        {
            path: '/',
            redirect: '/login',
        },
        // 捕获所有未匹配路由，重定向到登录页
        {
            path: '/:pathMatch(.*)*',
            redirect: '/login',
        },
    ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token');

    // 如果页面需要认证
    if (to.meta.requiresAuth && !token) {
        // 未登录则跳转到登录页
        next('/login');
    } else {
        // 已登录或不需要认证，正常跳转
        next();
    }
});

export default router;
